// pages/search-result/search-result.js
const app = getApp()

Page({
  data: {
    keyword: '',
    type: '',
    tickets: [],
    total: 0,
    currentPage: 1,
    pageSize: 20,
    hasMore: false,
    loading: false,
    refreshing: false
  },

  onLoad(options) {
    // 获取传递的参数
    const keyword = decodeURIComponent(options.keyword || '')
    const type = options.type || 'merchant'
    const tickets = JSON.parse(decodeURIComponent(options.tickets || '[]'))
    const total = parseInt(options.total || '0')

    // 为每个券添加过期状态
    const processedTickets = tickets.map(ticket => ({
      ...ticket,
      isExpired: this.isExpired(ticket.deadTime)
    }))

    this.setData({
      keyword: keyword,
      type: type,
      tickets: processedTickets,
      total: total,
      hasMore: type === 'merchant' && tickets.length < total // 只有商家搜索才支持加载更多
    })

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: `搜索结果 - ${keyword}`
    })
  },

  onShow() {
    // 页面显示时执行
  },

  // 判断券是否过期
  isExpired(deadTime) {
    if (!deadTime) return true
    const now = new Date()
    const expireDate = new Date(deadTime)
    return now > expireDate
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '无'
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 点击优惠券
  onTicketTap(e) {
    const ticket = e.currentTarget.dataset.ticket
    this.navigateToDetail(ticket)
  },

  // 查看详情
  onViewDetail(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation() // 阻止事件冒泡
    }
    const ticket = e.currentTarget.dataset.ticket
    this.navigateToDetail(ticket)
  },

  // 跳转到详情页
  navigateToDetail(ticket) {
    wx.navigateTo({
      url: `/pages/ticket-detail/ticket-detail?ticket=${encodeURIComponent(JSON.stringify(ticket))}`
    })
  },

  // 使用优惠券
  onUseTicket(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation() // 阻止事件冒泡
    }
    const ticket = e.currentTarget.dataset.ticket

    if (ticket.isExpired) {
      wx.showToast({
        title: '优惠券已过期',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '使用优惠券',
      content: `确定要使用券码 ${ticket.ticketCode} 吗？`,
      success: (res) => {
        if (res.confirm) {
          // 这里可以添加使用优惠券的逻辑
          wx.showToast({
            title: '使用成功',
            icon: 'success'
          })
          
          // 跳转到详情页查看使用详情
          // this.navigateToDetail(ticket)
          this.recordTicketUsage(ticket)
        }
      }
    })
  },

  // 记录优惠券使用
  recordTicketUsage(ticket) {
    // 显示使用成功的提示
    wx.showModal({
      title: '使用成功',
      content: `券码 ${ticket.ticketCode} 已成功使用！\n\n请向商家出示此页面完成核销。`,
      showCancel: false,
      confirmText: '知道了',
      success: () => {
        // 可以在这里添加跳转逻辑或其他操作
      }
    })

    // 这里可以调用后端API记录使用状态
    // wx.request({
    //   url: `${app.globalData.baseUrl}/qdd/ticket/use`,
    //   method: 'POST',
    //   data: {
    //     ticketId: ticket.ticketId
    //   },
    //   success: (res) => {
    //     // 处理使用结果
    //   }
    // })
  },

  // 加载更多
  loadMore() {
    if (this.data.loading || !this.data.hasMore || this.data.type !== 'goods') {
      return
    }

    this.setData({ loading: true })

    const nextPage = this.data.currentPage + 1

    wx.request({
      url: `${app.globalData.baseUrl}/qdd/ticket/detail/goods`,
      method: 'GET',
      data: {
        goodsName: this.data.keyword,
        page: nextPage,
        limit: this.data.pageSize
      },
      success: (res) => {
        this.setData({ loading: false })
        
        if (res.statusCode === 200 && res.data.code === 0) {
          const newTickets = res.data.data.list || []
          // 为新加载的券添加过期状态
          const processedNewTickets = newTickets.map(ticket => ({
            ...ticket,
            isExpired: this.isExpired(ticket.deadTime)
          }))
          const allTickets = [...this.data.tickets, ...processedNewTickets]

          this.setData({
            tickets: allTickets,
            currentPage: nextPage,
            hasMore: allTickets.length < this.data.total
          })
        } else {
          wx.showToast({
            title: '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        this.setData({ loading: false })
        console.error('加载更多失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  // 返回搜索页
  goBack() {
    wx.navigateBack()
  },

  // 下拉刷新
  onPullDownRefresh() {
    // 只有商品搜索才支持下拉刷新
    if (this.data.type !== 'goods') {
      this.setData({ refreshing: false })
      return
    }

    // 重新搜索第一页数据
    this.setData({
      currentPage: 1,
      loading: true,
      refreshing: true
    })

    wx.request({
      url: `${app.globalData.baseUrl}/qdd/ticket/detail/goods`,
      method: 'GET',
      data: {
        goodsName: this.data.keyword,
        page: 1,
        limit: this.data.pageSize
      },
      success: (res) => {
        this.setData({
          loading: false,
          refreshing: false
        })

        if (res.statusCode === 200 && res.data.code === 0) {
          const tickets = res.data.data.list || []
          // 为刷新的券添加过期状态
          const processedTickets = tickets.map(ticket => ({
            ...ticket,
            isExpired: this.isExpired(ticket.deadTime)
          }))
          this.setData({
            tickets: processedTickets,
            total: res.data.data.total,
            hasMore: processedTickets.length < res.data.data.total
          })
        }
      },
      fail: (err) => {
        this.setData({
          loading: false,
          refreshing: false
        })
        console.error('刷新失败:', err)
      }
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: `发现了${this.data.total}张"${this.data.keyword}"的优惠券`,
      path: `/pages/search/search`
    }
  },

  isExpired(datetime) {
    // 输出 datetime 的类型和值
    console.log("datetime 的类型:", typeof datetime);
    console.log("datetime 的值:", datetime);

    // 将字符串日期转换为时间戳
    const targetTime = new Date(datetime).getTime();
    // 获取当前时间戳
    const currentTime = new Date().getTime();

    // 判断是否过期
    return targetTime < currentTime;
  },
})
